<?php

namespace App\Http\Controllers\XhApi;

use App\Api\Sms\SmsClient;
use App\Models\Tokens;
use App\Repository\Sms\SmsSendLogRepository;
use App\Repository\Sms\SmsTmpRepository;
use App\Repository\XhApi\MemberRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

/**
 * @OA\Tag(
 *     name="后台用户登录模块",
 *     description="用户登录",
 * )
 */
class LoginController extends BaseController
{
    public $repoist;
    private $loginTime;

    public function __construct(MemberRepository $Repository)
    {
        $this->repoist = $Repository;
    }

    protected function code2Data($code)
    {
        $mini = config('xh.wxMini');
        $apiUrl = 'https://api.weixin.qq.com/sns/jscode2session';
        $response = Http::withOptions([
//            'debug' => true,
            'timeout' => 30,
            'connect_timeout' => 30,
            'read_timeout' => 30
        ])->get($apiUrl, [
            'appid' => $mini['appid'],
            'secret' => $mini['secret'],
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ]);
        return $response->json();
//        file_put_contents(storage_path('1.txt'), serialize($data));
//        return $data['openid'] ?? '';
    }

    public function byMini(Request $request)
    {
        $params = $request->all();
        $code = $params['code'] ?? '';
        $data = $this->code2Data($code);
        // 用户授权手机号登陆
        $openid = $data['openid'] ?? '';
        if (empty($openid)) {
            return $this->returnMsg(2, '获取授权异常');
        }
        $user = $this->repoist->unifiedGetOne(['mini_openid' => $openid]);
        if (empty($user)) {
            // 新注册
            $spread_id = $params['spid'] ?? 0;
            $userId = $this->repoist->newFromMini($openid, $spread_id);
            if ($userId <= 0) {
                return $this->returnMsg(2, '授权登陆异常');
            }
            $user = $this->repoist->unifiedGetOne(['id' => $userId]);
        }
        if ($user->status != 0) {
            return $this->returnMsg(102, '您已被停用');
        }
        $updateUser = [
            'login_ip' => $request->getClientIp(),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        $this->repoist->unifiedUpdate(['id' => $user->id], $updateUser);
//        取token
        $user->login_ip = $updateUser['login_ip'];
        $token = $this->_dealToken($user);
        $user['token'] = $token;
        return $this->returnMsg(200, '登陆成功', $user);
    }

    public function byApp(Request $request)
    {

    }

    /**
     * @OA\delete(
     *     path="/api/v1/logout",
     *     tags={"后台用户登录模块"},
     *     summary="登录退出",
     * @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}  "
     *     )
     * )
     */
    public function logout(Request $request)
    {
        $where['token'] = $request->header('token');
        $res = Tokens::where($where)->first();
        if ($res) {
            $res->delete();
        }
        return $this->returnMsg(200, '退出成功');
    }

    // 登录验证码
    public function sendLoginYanZhengMa(Request $Request)
    {
        // 最多五次 超过锁死 不允许登录  发送验证码
        $params = $Request->all();
        if (empty($params['mobile']) || !preg_match("/^1[3-9]\d{9}$/", $params['mobile'])) {
            return $this->returnMsg(102, '手机号不正确 ');
        }
        $user = $this->repoist->unifiedGetOne(['mobile' => $params['mobile']]);
        if (!$user) {
//            重新注册一个账号
            $spread_id = $params['spread_id'] ?? 0;
            $userId = $this->repoist->newFromMobile($params['mobile'], $spread_id);
        }
        $cacheFile = $params['mobile'] . '_login_nums';
        $cacheNums = Cache::get($cacheFile);
        if ($cacheNums > 5) {
            return $this->returnMsg(103, '您的账户频繁操作,请一小时后再试');
        }
        $captchaUuid = generate_uuid();
        $isTrue = $this->isCs();
        if ('13432453733' == $params['mobile']) {
            $isTrue = false;
        }
        $res = $this->sendSms($params['mobile'], $captchaUuid, $isTrue, 1);
        if (!empty($res['code']) && $res['code'] == 200) {
            if (empty($nums)) {
                $nums = 0;
            }
            $nums++;
            Cache::put($cacheFile, $nums, 3600);
            return $this->returnMsg(200, $res['msg'], ['captchaUuid' => $captchaUuid, 'code' => $res['data']['code'] ?? '']);
        }
        return $this->returnMsg(109, $res['msg']);
    }

    // 验证码登录
    public function loginSms(Request $request)
    {
        $params = $request->all();
        if (empty($params['code'])) {
            return $this->returnMsg(102, '验证码不能为空1');
        }
        if (empty($params['captchaUuid'])) {
            return $this->returnMsg(102, '验证码不能为空2');
        }
        if (empty($params['mobile']) || !preg_match("/^1[3-9]\d{9}$/", $params['mobile'])) {
            return $this->returnMsg(102, '手机号不正确 ');
        }
        $user = $this->repoist->unifiedGetOne(['mobile' => $params['mobile']]);
        if (empty($user)) {
            return $this->returnMsg(102, '手机号与验证码不正确 ');
        }
        if ($user->status != 0) {
            return $this->returnMsg(102, '您已被停用');
        }
        // 验证验证码 是否正确
        $params['phone'] = $params['mobile'];
        $isSmsCheck = $this->checkCaptchaSms($params);
        if (empty($isSmsCheck['code']) || $isSmsCheck['code'] != 200) {
            return $this->returnMsg(103, '验证码错误');
        }
        $updateUser = [
            'login_ip' => $request->getClientIp(),
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        $this->repoist->unifiedUpdate(['id' => $user->id], $updateUser);
//        取token
        $user->mobile = $params['mobile'];
        $user->login_ip = $updateUser['login_ip'];
        $token = $this->_dealToken($user);
        $list['data'] = $user;
        $list['data']['token'] = $token;
        return $this->returnMsg(200, '登陆成功', $list['data']);
    }

    private function _dealToken($user)
    {
        $days_time = time() . uniqid() . 'sltx@';
        $payload = array('id' => $user->id, 'user_id' => $user->id, 'ip' => $user->login_ip, 'time' => $days_time, 'mobile' => $user->mobile);
        $token = getTokenById($payload);
        $tokenWhere = ['user_id' => $user->id, 'user_from' => 1];
        $upData = [
            'user_id' => $user->id,
            'user_from' => 1,
            'user_name' => $user->mobile,
            'login_ip' => $user->login_ip,
            'role_id' => 0,
            'token' => $token,
            'created_at' => date('Y-m-d H:i:s')
        ];
        if (!Tokens::where($tokenWhere)->first()) {
            Tokens::insert($upData);
        } else {
            Tokens::where($tokenWhere)->update($upData);
        }
        return $token;
    }

    // 验证码验证
    public function checkCaptchaSms($data)
    {
        $captchaUuid = $data['captchaUuid'];
        $cacheFile = $data['phone'] . $captchaUuid . 'login_yzm';
        $res = Cache::get($cacheFile);
        if ($res != $data['code']) {
            return $this->returnMsg(-1, "验证失败");
        }
        Cache::put($cacheFile, 0, 0);
        return $this->returnMsg(200, "验证成功");
    }

    /**
     *  手机号
     *  UUID
     *  是否是测试环境
     * 类型 1 登录  2 注册
     */
    public function sendSms($phone, $uuid, $isTrue = true, $type = 1)
    {
        // $model = new TransferSms();
        $num = mt_rand(000000, 999999);
        // $content = '【验证码】本次导出密码:' . $num;
        if ($type == 1) {
            $content = '【乔乔通信】本次登录验证码:' . $num . '，请勿告诉其他人';
        }
        if ($type == 2) {
            $content = '【乔乔通信】本次注册验证码:' . $num . '，请勿告诉其他人';
        }
//        $content = '【乔乔通信】您的验证码为' . $num . '，该验证码5分钟内有效。请勿泄漏于他人。';

        // $uuid = generate_uuid();
        // $phone = '15225070393';
//        $phone = $phone;
//        $tmpData = [
//            'phone' => $phone,
//            'content' => $content
//        ];
        //将验证码存入缓存
        Cache::put($phone . $uuid . 'login_yzm', $num);
        if ($isTrue) {
//            获取短信模板内容
            $Repository = new SmsTmpRepository();
            $row = $Repository->unifiedGetOne(['name' => '登陆与注册'], ['id', 'tpl_id', 'name', 'content']);
            if (empty($row)) {
                return [
                    'code' => 1,
                    'msg' => '请先审核一个名为:登陆与注册的模板后再操作',
                ];
            }
//            $content = str_replace('{1}', $num, $row['content']);
//            print_r($row);
            $SmsApi = new SmsClient();
            $tplParamsData = ['code' => $num];
            $res = $SmsApi->sendSmsByTpl($phone, $row['tpl_id'], $row['type'], $row['content'], $tplParamsData);
            $content = $SmsApi->parseTplContent($row['content'], $tplParamsData);
//            记录发送日志
//            $res['data']['smsId'] = '1123213528019378904593';
            $LogRepository = new SmsSendLogRepository();
            $LogRepository->add([
                'sms_id' => $res['data']['smsId'],
                'sms_tmp_name' => $row['name'],
                'sms_tmp_id' => $row['id'],
                'content' => $content,
                'order_id' => 0,
                'shop_id' => 1
            ]);
            $res = [
                'code' => 200,
                'msg' => '验证码发送成功,请及时输入！',
                'data' => []
            ];
        }
        if (!$isTrue) {
            $res = [
                'code' => 200,
                'msg' => '测试环境发送成功',
                'data' => ['code' => $num]
            ];
        }

        // if(!empty($res['data'])){
        //   $res['data']['nums'] = $num;
        // }
        return $res;
    }

    // 判断是否是 测试环境
    public function isCs()
    {
        $isTrueSms = true;
//        var_dump($_SERVER, 1111111);
        if (!empty($_SERVER['HTTP_HOST']) && $_SERVER['HTTP_HOST'] == 'mycard.com') {
            $isTrueSms = false;
        }
        return $isTrueSms;
    }
}
